package com.beichuan_travel.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beichuan_travel.enums.ResultCode;
import com.beichuan_travel.exception.ApiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class WeChatUtils {

    @Value("${weixin.login.url}")
    private String requestUrl;

    @Value("${weixin.login.app-id}")
    private String appid;

    @Value("${weixin.login.login-secret}")
    private String secret;

    @Value("${weixin.login.grant-type}")
    private String grantType;

    public JSONObject getSessionKeyOrOpenId(String code) {
        Map<String, String> requertUrlParam = new HashMap<>();

        // 小程序appid
        requertUrlParam.put("appid", appid);
        // 小程序secret
        requertUrlParam.put("secret", secret);
        // 小程序端返回的code
        requertUrlParam.put("js_code", code);
        // 默认参数
        requertUrlParam.put("grant_type", grantType);
        // 发送post请求读取调用微信接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(HttpClientUtils.doPost(requestUrl, requertUrlParam));
        if (jsonObject.containsKey("errcode")) {
            throw new ApiException(ResultCode.VALIDATE_FAILED, "非法code");
        }
        return jsonObject;
    }

}
